<template>
  <div class="h-full p-4">
    <!-- Alert Container with white background -->
    <div class="h-full flex flex-col bg-white rounded-lg shadow p-6 min-h-0">
      <!-- Filter section -->
      <div class="mb-6">
        <!-- Tab buttons -->
        <div class="mb-4">
          <CustomTabs v-model="activeTab" :tabs="tabs" @change="handleTabChange" />
        </div>

        <!-- Search filters -->
        <div class="flex items-center space-x-4">
          <el-input v-model="filters.alertCode" placeholder="Alert code/SN" clearable class="!w-60">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>

          <el-date-picker v-model="dateRange" type="date" placeholder="Select date" class="!w-48" />

          <el-select v-model="filters.product" placeholder="All device model" clearable class="!w-48">
            <el-option v-for="item in productOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>

          <div class="flex items-center space-x-2 ml-auto">
            <el-button @click="resetFilters">Reset</el-button>
            <el-button type="primary" @click="searchAlerts">Search</el-button>
          </div>
        </div>
      </div>

      <!-- Table section -->
      <div class="flex-1 overflow-auto">
        <PageState :loading="loading" :error-message="errorMessage" :has-data="displayedAlertList.length > 0"
          @retry="retryFetch">
          <el-table :data="displayedAlertList" style="width: 100%"
            :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#606266' }">
            <el-table-column prop="alertCode" label="Alert Code" width="120" align="center" />
            <el-table-column prop="alertName" label="Alert Name" min-width="200" align="center" />
            <el-table-column prop="deviceName" label="Device Name" min-width="180" align="center" />
            <el-table-column prop="sn" label="SN" min-width="140" align="center" />
            <el-table-column prop="product" label="Product" min-width="120" align="center" />
            <el-table-column prop="faultyModule" label="Faulty Module" min-width="120" align="center" />
            <el-table-column label="Occurrence Time" min-width="160" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.occuranceTime) }}
              </template>
            </el-table-column>
            <el-table-column label="Recover Time" min-width="160" align="center">
              <template #default="scope">
                <span v-if="scope.row.recoveryTime">
                  {{ formatDateTime(scope.row.recoveryTime) }}
                </span>
                <span v-else class="text-orange-500">—</span>
              </template>
            </el-table-column>
            <el-table-column label="Operate" width="100" fixed="right" align="center">
              <template #default="scope">
                <el-button type="primary" link @click="showDetails(scope.row)">
                  Details
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </PageState>
      </div>

      <!-- Pagination -->
      <div class="ml-auto p-4">
        <el-pagination class="ml-auto" v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize" background :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- Alert Details Dialog -->
    <el-dialog v-model="dialogVisible" title="Alert Details" width="800px" :before-close="handleClose">
      <div class="alert-details-content">
        <!-- Basic Information Section with Border -->
        <div class="info-section">
          <div class="grid grid-cols-2 gap-x-8 gap-y-4">
            <div class="detail-item">
              <span class="label">Alert ID</span>
              <span class="value">{{ alertDetails.alertCode }}</span>
            </div>
            <div class="detail-item">
              <span class="label">Alert name</span>
              <span class="value">{{ alertDetails.alertName }}</span>
            </div>
            <!-- <div class="detail-item">
              <span class="label">System ID</span>
              <span class="value">{{ alertDetails.systemId }}</span>
            </div>
            <div class="detail-item">
              <span class="label">System name</span>
              <span class="value">{{ alertDetails.systemName }}</span>
            </div> -->
            <div class="detail-item">
              <span class="label">Device name</span>
              <span class="value">{{ alertDetails.deviceName }}</span>
            </div>
            <div class="detail-item">
              <span class="label">SN</span>
              <span class="value">{{ alertDetails.sn }}</span>
            </div>
            <div class="detail-item">
              <span class="label">Faulty module</span>
              <span class="value">{{ alertDetails.faultyModule }}</span>
            </div>
            <div class="detail-item">
              <span class="label">Product</span>
              <span class="value">{{ alertDetails.product }}</span>
            </div>
            <div class="detail-item">
              <span class="label">Occurance time</span>
              <span class="value">{{
                formatDateTime(alertDetails.occuranceTime)
              }}</span>
            </div>
            <div class="detail-item">
              <span class="label">Recovery time</span>
              <span class="value">{{
                alertDetails.recoveryTime
                  ? formatDateTime(alertDetails.recoveryTime)
                  : "—"
              }}</span>
            </div>
          </div>
        </div>

        <!-- Possible Reason Section with Border -->
        <div v-if="alertDetails.possibleReason" class="reason-section">
          <h3 class="section-title">Possible Reason</h3>
          <p class="section-content">{{ alertDetails.possibleReason }}</p>
        </div>

        <!-- Suggestion Section with Border -->
        <div v-if="alertDetails.suggestions && alertDetails.suggestions.length" class="suggestion-section">
          <h3 class="section-title">Suggestion</h3>
          <ol class="suggestion-list">
            <li v-for="(suggestion, index) in alertDetails.suggestions" :key="index" class="suggestion-item">
              {{ suggestion }}
            </li>
          </ol>
        </div>
      </div>

      <template #footer>
        <span class="flex justify-end">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="dialogVisible = false">OK
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch } from "vue";
import { Search } from "@element-plus/icons-vue";
import CustomTabs from "@/components/CustomTabs";
import PageState from "@/components/base/PageState.vue";
import { useDebounce } from "@/utils/utils";
import { alertApi } from "@/api/business";

// Props
const props = defineProps<{ systemId: string }>();

// Alert types
interface AlertItem {
  id: string;
  alertCode: string;
  alertName: string;
  // systemId: string;
  // systemName: string;
  deviceName: string;
  sn: string;
  product: string;
  faultyModule: string;
  occurrences: number;
  status: "active" | "resolved";
  occuranceTime: string;
  recoveryTime: string | null;
  deviceModel: string;
  possibleReason: string;
  suggestions: string[];
}

// 真实数据：由接口返回

// State
const activeTab = ref("Active");
const dateRange = ref(null);
const filters = reactive({
  alertCode: "",
  product: "All device model"
});

// 状态管理
const loading = ref(false);
const errorMessage = ref("");

// 标签配置
const tabs = [
  { name: "All", label: "All" },
  { name: "Active", label: "Active" },
  { name: "Historical", label: "Historical" }
];

// Product options - 动态获取
const productOptions = ref([
  { value: "All device model", label: "All device model" }
]);

// Pagination
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 当前页数据
const displayedAlertList = ref<AlertItem[]>([]);

// 获取Product选项
const loadProductOptions = async () => {
  try {
    // 这里需要根据实际API接口来调用
    // 假设有一个获取产品列表的接口
    const params = {
      id: Number(props.systemId) || props.systemId
    };
    
    // 临时方案：从告警数据中提取不重复的product字段
    const res: any = await alertApi.getPage({ ...params, limit: 1000 });
    if (res?.code === 0 && Array.isArray(res?.data?.list)) {
      const products = new Set<string>();
      res.data.list.forEach((item: any) => {
        if (item.deviceModel) {
          products.add(item.deviceModel);
        }
      });
      
      // 构建选项数组，保留"All device model"选项
      const options = [{ value: "All device model", label: "All device model" }];
      Array.from(products).forEach(product => {
        options.push({ value: product, label: product });
      });
      
      productOptions.value = options;
      console.log('[Alerts] Product options loaded:', productOptions.value);
    }
  } catch (error) {
    console.error('[Alerts] Failed to load product options:', error);
    // 保持默认选项
  }
};

// 加载真实数据（Web 端）
const loadAlerts = async () => {
  loading.value = true;
  errorMessage.value = "";
  try {
    const params: any = {
      page: pagination.currentPage,
      limit: pagination.pageSize,
      // 文档字段要求
      id: Number(props.systemId) || props.systemId
    };
    // 关键词：AlertID/Name/SN
    if (filters.alertCode) params.search = filters.alertCode.trim();
    // 设备型号
    if (filters.product && filters.product !== "All device model") params.deviceModel = filters.product;
    // 日期：单日-> startTime/endTime 同一天
    if (dateRange.value) {
      const d = new Date(dateRange.value as any);
      const y = d.getFullYear();
      const m = String(d.getMonth() + 1).padStart(2, "0");
      const da = String(d.getDate()).padStart(2, "0");
      const ds = `${y}-${m}-${da}`;
      params.startTime = ds;
      params.endTime = ds;
    }
    // 故障状态：0:All和Active, 1:Historical  
    params.faultStatus = activeTab.value === 'Historical' ? 1 : 0;

    console.log('[Alerts] loadAlerts params:', params);

    const res: any = await alertApi.getPage(params);
    console.log('[Alerts] API response:', res);
    if (res?.code === 0) {
      const list = Array.isArray(res?.data?.list) ? res.data.list : [];
      console.log(`[Alerts] mapped list length: ${list.length}`);
      displayedAlertList.value = list.map((x: any) => ({
        alertCode: x.code,
        alertName: x.alertName,
        deviceName: x.deviceName,
        sn: x.sn,
        product: x.deviceModel,
        faultyModule: x.faultyModule,
        occuranceTime: x.occurrenceTime,
        recoveryTime: x.recoveryTime,
        possibleReason: x.possibleReason,
        suggestions: Array.isArray(x.suggestions) ? x.suggestions : (x.suggestions ? [x.suggestions] : [])
      }));
      pagination.total = Number(res?.data?.total || list.length);
    } else {
      errorMessage.value = res?.msg || "Failed to load alerts";
      displayedAlertList.value = [];
      pagination.total = 0;
    }
  } catch (e: any) {
    console.warn('[Alerts] loadAlerts error:', e);
    errorMessage.value = e?.message || "Failed to load alerts";
    displayedAlertList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// Alert details dialog
const dialogVisible = ref(false);
const alertDetails = reactive<AlertItem>({
  id: "",
  alertCode: "",
  alertName: "",
  // systemId: "",
  // systemName: "",
  deviceName: "",
  sn: "",
  product: "",
  faultyModule: "",
  occurrences: 0,
  status: "active",
  occuranceTime: "",
  recoveryTime: null,
  deviceModel: "",
  possibleReason: "",
  suggestions: []
});

// Methods
const formatDateTime = (dateString: string) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const resetFilters = () => {
  console.log('[Alerts] resetFilters');
  filters.alertCode = "";
  filters.product = "All device model";
  dateRange.value = null;
  pagination.currentPage = 1;
  loadAlerts();
};

const searchAlerts = () => {
  console.log('[Alerts] searchAlerts with filters:', { ...filters, date: dateRange.value });
  pagination.currentPage = 1;
  loadAlerts();
};

const handleTabChange = () => {
  console.log('[Alerts] tab change ->', activeTab.value);
  pagination.currentPage = 1;
  loadAlerts();
};

const handleSizeChange = (val: number) => {
  console.log('[Alerts] pageSize change ->', val);
  pagination.pageSize = val;
  pagination.currentPage = 1;
  loadAlerts();
};

const handleCurrentChange = (val: number) => {
  console.log('[Alerts] page change ->', val);
  pagination.currentPage = val;
  loadAlerts();
};

const showDetails = (row: AlertItem) => {
  Object.assign(alertDetails, row);
  dialogVisible.value = true;
};

const handleClose = () => {
  dialogVisible.value = false;
};

onMounted(() => {
  loadProductOptions();
  loadAlerts();
});

// 重试加载
const retryFetch = () => {
  loadAlerts();
};

// 防抖搜索
const debouncedSearch = useDebounce(() => {
  searchAlerts();
}, 500, { leading: false, trailing: true });
</script>

<style lang="scss" scoped>
/* 调整分页组件样式 */
:deep(.el-pagination) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-pagination .el-pagination__total) {
  margin-right: auto;
}

:deep(.el-pagination .el-pagination__jump) {
  margin-left: auto;
}

// 取消分页器非活跃按钮的背景色
:deep(.el-pagination .el-pager li) {
  background-color: transparent;
}

/* Alert Details Dialog Styles */
.alert-details-content {
  padding: 0;

  // Common styles for all bordered sections
  .info-section,
  .reason-section,
  .suggestion-section {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 16px;
    margin-bottom: 16px;
    background-color: #fff;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .detail-item {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .label {
      color: #909399;
      font-size: 14px;
      font-weight: normal;
    }

    .value {
      color: #303133;
      font-size: 14px;
      font-weight: 500;
      text-align: right;
    }
  }

  .section-title {
    color: #303133;
    font-size: 16px;
    font-weight: 600;
    margin: 0 0 12px 0;
  }

  .section-content {
    color: #606266;
    font-size: 14px;
    line-height: 1.6;
    margin: 0;
  }

  .suggestion-list {
    margin: 0;
    padding-left: 20px;

    .suggestion-item {
      color: #606266;
      font-size: 14px;
      line-height: 1.6;
      margin-bottom: 8px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

:deep(.el-dialog__header) {
  padding: 20px 20px 0 20px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 0 20px 20px 20px;
}
</style>
